using B.S.XZYData.Api.Read.Application.Command.SalesOrder;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using SqlSugar;

namespace B.S.XZYData.Api.Read.Application.Handler.SalesOrder
{
    /// <summary>
    /// 获取产品选择列表处理器
    /// </summary>
    public class GetProductSelectHandler : IRequestHandler<GetProductSelectCommand, ApiResult<ApiPageing<ProductSelectDTO>>>
    {
        private readonly IBaseRepository<ProductModel> _productRepo;

        public GetProductSelectHandler(IBaseRepository<ProductModel> productRepo)
        {
            _productRepo = productRepo;
        }

        public async Task<ApiResult<ApiPageing<ProductSelectDTO>>> Handle(GetProductSelectCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var query = _productRepo.GetAll();

                // 产品编号筛选
                if (!string.IsNullOrEmpty(request.ProductCode))
                {
                    query = query.Where(x => x.Code.Contains(request.ProductCode));
                }

                // 产品名称筛选
                if (!string.IsNullOrEmpty(request.ProductName))
                {
                    query = query.Where(x => x.Name.Contains(request.ProductName));
                }

                // 按产品编号排序
                query = query.OrderBy(x => x.Code);

                // 分页查询
                var total = await query.CountAsync();
                var list = await query
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync();

                // 转换为DTO
                var dtoList = list.Select(x => new ProductSelectDTO
                {
                    Id = x.Id,
                    Code = x.Code,
                    Name = x.Name,
                    Spec = x.Spec,
                    Unit = x.Unit
                }).ToList();

                var result = new ApiPageing<ProductSelectDTO>
                {
                    TotaCount = total,
                    PageData = dtoList
                };

                return ApiResult<ApiPageing<ProductSelectDTO>>.Success(result);
            }
            catch (Exception ex)
            {
                return ApiResult<ApiPageing<ProductSelectDTO>>.Error($"获取产品选择列表失败：{ex.Message}");
            }
        }
    }
}
